<?php

namespace App\Console\Commands;

use App\Models\GrGood;
use App\Models\GrRefund;
use App\Models\GrUser;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Refund extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'Refund';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        //查询出商家同意退款的订单
        $data = GrRefund::join('order', 'gr_refund.order_id', '=', 'order.id')
            ->where('refund_status', 1)->where('is_refund', 0)->get()->toArray();
        if (!empty($data)) {
            foreach ($data as $k => $v) {
                //判断是余额宝
                if ($v['pay_type'] == 0) {
                    //开启事物
                    DB::beginTransaction();
                    try {
                        //判断商家余额是否充足
                        if (GrUser::where('id', $v['merchant_id'])->first()->balance - $v['back_money'] < 0) {
                            Log::info($v['merchant_id'] . "余额不足");
                            return false;
                        } else {
                            //商家余额减少
                            $res = GrUser::where('id', $v['merchant_id'])->update(['balance' => GrUser::where('id', $v['merchant_id'])->first()->balance - $v['back_money']]);
                            if ($res) {
                                //用户余额增加
                                GrUser::where('id', $v['user_id'])->update(['balance' => GrUser::where('id', $v['user_id'])->first()->balance + $v['back_money']]);
                                //修改状态，已退款
                                GrRefund::where('refund_id', $v['refund_id'])->update(['is_refund' => 1]);
                                //恢复库存
                                $orderData = \App\Models\OrderGoods::join('gr_goods', 'gr_order_goods.goods_id', '=', 'gr_goods.goods_id')
                                    ->where('order_id', $v['order_id'])->get()->toArray();
                                foreach ($orderData as $kk => $vv) {
                                    $result = GrGood::where('goods_id', $vv['goods_id'])->update(['stock_total' => $vv['goods_number'] + $vv['stock_total']]);
                                }
                            }
                            DB::commit();
                            if ($result) {
                                Log::info($v['user_id'] . "余额宝退款成功");
                            } else {
                                Log::info($v['user_id'] . "退款失败");
                            }
                        }
                    } catch (\Exception $e) {
                        //回滚事务
                        Db::rollback();
                    }

                } else {
                    //判断是支付宝
                    DB::beginTransaction();
                    try {
                        //支付宝退款
                        $aliPay = new \App\service\AlipayController();
                        $res = $aliPay->refund($v['order_sn'], $v['back_money']);
                        if ($res->msg == "Success") {
                            //修改状态
                            GrRefund::where('refund_id', $v['refund_id'])->update(['is_refund' => 1]);
                            $orderData = \App\Models\OrderGoods::join('gr_goods', 'gr_order_goods.goods_id', '=', 'gr_goods.goods_id')
                                ->where('order_id', $v['order_id'])->get()->toArray();
                            foreach ($orderData as $kk => $vv) {
                                $result = GrGood::where('goods_id', $vv['goods_id'])->update(['stock_total' => $vv['goods_number'] + $vv['stock_total']]);
                            }
                        }
                        DB::commit();
                        if ($result) {
                            Log::info('支付宝退款成功');
                        } else {
                            Log::info("支付宝退款失败");
                        }
                   } catch (\Exception $e) {
                       //回滚事务
                       Db::rollback();
                    }
                }

            }
        }
    }
}
